<!--
 * @Descripttion: 登录页面
 * @version:
 * @Author: lhl
 * @Date: 2024-09-11 16:05:03
 * @LastEditors: lhl
 * @LastEditTime: 2024-09-17 20:55:39
-->

<template>
  <el-watermark :content="LOGIN_WATER_TXT">
    <div class="login-container">
      <!-- 使用element-plus的表单写一个登录页面 -->
      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="loginRules"
        label-width="auto"
        class="login-form"
      >
        <h1 class="animate__animated animate__shakeY">Element-plus 后台管理系统</h1>
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input
            v-model.trim="form.username"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input
            type="password"
            v-model.trim="form.password"
            placeholder="请输入密码"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="验证码"
          prop="code"
          class="code-item"
        >
          <el-input
            v-model.trim="form.code"
            placeholder="请输入验证码"
            :maxlength="4"
            show-word-limit
            clearable
          ></el-input>
          <img
            class="captcha-image"
            alt="验证码"
            src=""
          />
        </el-form-item>
        <!-- 是否记住密码 -->
        <el-form-item>
          <el-checkbox v-model="form.remember">记住密码</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm(ruleFormRef)"
            class="login-button"
            >登录</el-button
          >
        </el-form-item>
        <h3 class="animate__animated animate__shakeY">Copyright (c) 2024 鱼樱前端</h3>
      </el-form>
    </div>
  </el-watermark>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus';
import { LOGIN_WATER_TXT } from '@/constant';
import { useUserInfo } from '@/store/user';

interface FormData {
  username: string;
  password: string;
  code: string;
  remember: boolean;
}
const form = ref<FormData>({
  username: 'admin',
  password: '123456',
  code: 'fAbB',
  remember: true
});

const ruleFormRef = ref<FormInstance>();
const router = useRouter();
const route = useRoute();
// 处理重定向逻辑：在某些情况下，redirect 参数可能用于在用户登录后将其重定向到特定页面
const redirect = ref('');
const otherQuery = ref({});

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '长度为 4', trigger: 'blur' }
  ]
};

/**
 * 获取除redirect外的其他查询参数
 * @param query 查询参数对象
 * @returns 返回一个不包含redirect字段的查询参数对象
 */
const getOtherQuery = (query: any) => {
  return Object.keys(query).reduce((acc: any, cur: any) => {
    if (cur !== 'redirect') {
      acc[cur] = query[cur];
    }
    return acc;
  }, {});
};

watch(
  route,
  () => {
    const query = route.query;
    if (query) {
      redirect.value = query.redirect as string;
      otherQuery.value = getOtherQuery(query);
    }
  },
  {
    immediate: true
  }
);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  try {
    // 验证表单
    const valid = await formEl.validate();
    if (!valid) {
      return;
    }

    // 调用登录接口
    const res = await useUserInfo().login(form.value);
    console.log('登录成功:', res);
    if (res.code === 200) {
      // 跳转到首页或其他页面
      console.log(redirect.value, 'redirect.value');
      router.push({ path: redirect.value || '/', query: otherQuery.value }).catch((error) => {
        console.error('路由跳转失败:', error);
      });
    }
  } catch (error) {
    console.error('请求失败:', error);
    // 可以添加用户友好的提示，例如使用通知组件通知用户登录失败或其他错误信息
    // notify.error('登录失败，请重试');
  }
};
</script>

<style lang="scss" scoped>
@keyframes gradient-animation {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

/* 媒体查询，适配小于768px的屏幕 */
@media (width <= 768px) {
  .login-container {
    align-items: flex-start; // 调整垂直对齐方式
    padding: 20px; // 增加内边距来适应小屏幕上的空间
  }

  h1,
  h3 {
    font-size: 14px; // 调整标题字号
  }

  .login-form {
    padding: 10px; // 减小内边距
  }
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px; // 增加内边距以适应移动端的屏幕
  height: 100vh;
  background: linear-gradient(45deg, #ff7e5f, #feb47b, #76b852, #8dc26f);
  background-size: 400% 400%;
  animation: gradient-animation 15s ease infinite;

  .login-form {
    padding: 20px;
    width: 100%; // 使用百分比宽度
    max-width: 400px; // 设置最大宽度
    background-color: rgb(255 255 255 / 90%);
    border-radius: 10px;
    box-shadow: 0 4px 8px rgb(0 0 0 / 10%);

    .login-button {
      width: 100%;
    }

    .code-item {
      display: flex;
      align-items: center;
      flex-wrap: wrap; // 允许内容换行，以适应小屏幕

      .el-input {
        margin-right: 10px;
        width: calc(100% - 110px);
        // 使用calc函数保证在小屏幕时输入框和验证码图片能够合理布局
      }

      .captcha-image {
        width: 100px; // 确保验证码图片不会过大
        height: 30px;
        border: 1px solid #ccc;
        border-radius: 4px;
        flex-shrink: 0; // 禁止图片缩小
      }
    }
  }
}

h1 {
  font-size: 24px;
  text-align: center;
}

h3 {
  font-size: 16px;
  font-weight: normal;
  text-align: center;
}
</style>
